<template>
  <el-button
      v-bind="props"
      icon="Edit"
      @click="handleUpdate"
      v-show="props.show"
  >{{ props.label}}</el-button>
</template>

<script lang="ts" setup>
import eventBus from '@/event/eventBus';
import {listInterfaceAll,convert2ApiJson,doRequest,findPathsByCondition,getValueByPath,convertReturnValueToFlatten} from '@/api/business/interface'
import {replaceDynamicVar} from '@/api/tool/replacevar'
import {
  setRowDataKey,showDialogKey,setValueKey,insertOrUpdateFlagKey
} from "@/config/app.keys";
import {onMounted, onUnmounted, ref, watch,inject} from "vue";
import {ElMessage} from "element-plus";


interface Props {
  size?:string
  type?:string
  plain?:boolean
  text?:boolean
  bg?:boolean
  link?:boolean
  round?:boolean
  circle?:boolean
  loading?:boolean
  disabled?:boolean
  autofocus?:boolean
  formData?:object
  id?:string,
  label?: string,
  btId?:string//按钮本身id
  bindDialog?:string//绑定弹窗的id，通常修改时弹出框显示
  operationdata?:object//操作数据
  bindButton?:string//绑定的提交按钮
  dialogTitle?:string// 弹出对话框标题
  show?:boolean,//是否显示
}
const props = withDefaults(defineProps<Props>(), {
  label: '编辑',
  id: 0,
  type:"success",
  show:true,
})
const id = ref(0);
const form = ref({});
const selectRow = ref({})
const formMode = inject(formModeKey)
const cMode = computed<FormFieldMode>(() => {
  if (props.mode) {
    return props.mode
  }
  if (formMode?.value) {
    return formMode.value
  }
  return "edit"
})
watch(() => props.id, (newVal) =>{
  console.log('props.id:'+newVal)
})
onMounted(() => {
  eventBus.$on(props.id+"_"+setRowDataKey, (data) => {
    selectRow.value = data
  })

})

onUnmounted(() =>{
  eventBus.$off(props.id+"_"+setRowDataKey);
})

/** 更新按钮操作 */
async function handleUpdate() {
  // 只有在 edit 模式下才执行删除操作
  if (cMode.value !== 'edit') {
    return;
  }
  //替换变量值
  let opertionParameter = JSON.stringify(props.operationdata.parameterList);
  let contextMap = new Map();

  console.log('props.formData:' + JSON.stringify(selectRow.value))
  const propertyCount = Object.keys(selectRow.value).length;
  if(propertyCount==0){
    return;
  }
  let replaceParameters = replaceDynamicVar(selectRow.value, contextMap, opertionParameter)

  //将replaceParameters转换为json对象
  let jsonParameters = JSON.parse(replaceParameters);
  //调用API
  //根据接口编码查询接口信息
  let interfaceParam = {"interfaceCode": props.operationdata.interfaceCode};
  let interfaceInfo = await listInterfaceAll(interfaceParam);
  if (interfaceInfo.code === 200) {
    //调用接口
    let searchParameter = convert2ApiJson(jsonParameters)
    let apiParameter = {};

    //判断接口为get,且不是通用接口时，则拼接到后面
    if (interfaceInfo.data[0].interfaceMethod == 'GET') {
      apiParameter = searchParameter;
      //尝试替换url中的变量
      interfaceInfo.data[0].interfaceUrl = replaceDynamicVar(selectRow.value, contextMap, interfaceInfo.data[0].interfaceUrl);
    } else {
      //如果是通用,则单独一个searchConditon
      if (interfaceInfo.data[0].isCommonUrl == 'Y') {
        apiParameter = searchParameter;
        apiParameter["interfaceCode"] = props.operationdata.interfaceCode
      } else {
        //将searchParameter合并到apiParameter
        apiParameter = searchParameter;
      }
    }
    let res = await doRequest(interfaceInfo.data[0], apiParameter);

    if (res.code === 200) {

      // form.value = res.data;
      eventBus.$emit(props.bindDialog+"_"+showDialogKey, {show:true,title: props.dialogTitle,form:{}});
      //通知所有绑定的组件更新值
      notifyAllBindCtrl(props.operationdata.returnValueList,res);
      //通知提交按钮
      if(props.bindButton){
        eventBus.$emit(props.bindButton+"_"+insertOrUpdateFlagKey,false)
      }
    } else {
      ElMessage.error(res.msg || '操作失败！')
    }
  }


}
let bindComponents = [];
//通知所有绑定组件更新值
function notifyAllBindCtrl(returnValueList,response){
  if(bindComponents.length==0) {
    //搜索returnValueList中绑定组件的json路径列表
    const condition = (value, prefix, suffix) => {
      return value.toString().startsWith(prefix) && value.toString().endsWith(suffix);
    };
    const prefix = "${";
    const suffix = "}";
    let flattenJosn = convertReturnValueToFlatten(returnValueList)
    const bindCompJsonPaths = findPathsByCondition(flattenJosn, (v) => condition(v, prefix, suffix));
    //循环json路径列表，获取绑定组件id,并放入一个json数组

    for (let i = 0; i < bindCompJsonPaths.length; i++) {
      let jsonPath = bindCompJsonPaths[i];
      let jsonPathValue = getValueByPath(flattenJosn, jsonPath);
      let item = {
        jsonPath: jsonPath,
        componentId: jsonPathValue.substring(2, jsonPathValue.length - 1)
      }
      bindComponents.push(item);
    }
  }
  //循环json数组，根据json路径，获取值，并更新绑定组件的值
  for(let i = 0; i < bindComponents.length; i++){
    let jsonPath = bindComponents[i].jsonPath;
    let componentId = bindComponents[i].componentId;
    let jsonPathValue = getValueByPath(response, jsonPath);
    // console.log(componentId + "_" + setValueKey+","+jsonPathValue)
    let timer = null;
    timer = setTimeout(() => {
      eventBus.$emit(componentId + "_" + setValueKey, jsonPathValue);
      clearTimeout(timer);
    },100);
  }
}
</script>

<style scoped>

</style>
